<template>
    <view>
        <view v-if="isLoad === null" class="margin-top load notexist text-l text-grey"></view>
        <view v-if="isLoad === false" class="margin-top load loading text-l text-grey"></view>

        <block v-if="isAdmin && isLoad">
            <cmpt-comm-list
                id="cmpt-comm-list"
                type="admin-meet-join-list"
                :search="search"
                :_params="params_var"
                :_menus="sortMenus"
                :_items="sortItems"
                route="admin/meet_join_list"
                topBottom="50"
                placeholder="搜索"
                sortMenusDefaultIndex="0"
                @list="bindCommListCmpt($event, { tagId: 'cmpt-comm-list' })"
            >
                <view slot="searchEnd">
                    <button @tap="url" :data-url="'../self/admin_meet_self?mark=' + mark + '&title=' + titleEn" class="btn radius mid bg-blue margin-right-xs">自助签到码</button>
                    <button @tap="bindCancelAllTap" class="btn mid radius bg-orange margin-right-xs">取消所有</button>
                </view>

                <!-- List Begin -->
                <view class="join-list">
                    <view class="time-line text-grey">({{ time }})</view>
                    <view v-if="dataList && dataList.total" class="load text-grey">
                        共有{{ dataList.total }}条符合条件记录
                        <text v-if="isAllFold" @tap="bindUnFoldAllTap" class="margin-left-xs icon-unfold text-admin">全部展开</text>
                        <text v-else @tap="bindFoldAllTap" class="margin-left-xs icon-fold text-admin">全部收起</text>
                    </view>

                    <view class="item" v-for="(item, index) in dataList.list" :key="index">
                        <view class="header">
                            <view class="left">
                                <text class="icon-calendar margin-right-xxs"></text>
                                <text class="">{{ item.JOIN_MEET_DAY }} ({{ item.JOIN_MEET_TIME_START }}～{{ item.JOIN_MEET_TIME_END }})</text>
                            </view>
                            <view class="right" @tap="bindCopyTap" :data-idx="index">
                                <text class="icon-copy margin-right-xxs"></text>
                                复制资料
                            </view>
                        </view>

                        <view class="info">
                            <view class="info-item">
                                <view class="title text-admin">状态</view>
                                <view class="mao">：</view>
                                <view class="content">
                                    <view v-if="item.JOIN_STATUS == 1" class="text-black">
                                        <text class="icon-roundcheck margin-right-xxs"></text>
                                        预约成功
                                        <text v-if="item.JOIN_IS_CHECKIN == 1">，已签到</text>
                                        <text class="text-grey" v-else>，未签到</text>
                                    </view>
                                    <view v-else-if="item.JOIN_STATUS == 10">用户取消</view>
                                    <view v-else-if="item.JOIN_STATUS == 99">系统取消</view>
                                </view>
                            </view>

                            <view class="info-item" v-if="item.JOIN_STATUS == 99">
                                <view class="title text-admin">取消原因</view>
                                <view class="mao">：</view>
                                <view class="content">{{ item.JOIN_REASON || '未填' }}</view>
                            </view>
                            <view class="info-item" v-if="item.JOIN_STATUS == 8">
                                <view class="title text-orange">未通过原因</view>
                                <view class="mao">：</view>
                                <view class="content">{{ item.JOIN_REASON || '未填' }}</view>
                            </view>

                            <view class="info-item" v-if="formindex < 3 || !item.fold" v-for="(form, formindex) in item.JOIN_FORMS" :key="formindex">
                                <view class="title">{{ form.title }}</view>

                                <view class="mao">：</view>

                                <view v-if="form.type == 'mobile'" class="content" @tap="url" data-type="phone" :data-url="form.val">
                                    <text :class="valItem === search ? 'text-red text-bold' : ''" v-for="(valItem, index) in form.valArr" :key="index">{{ valItem }}</text>
                                    <text class="margin-left-xs icon-phone text-black text-normal"></text>
                                </view>

                                <view v-else class="content" @tap="url" data-type="copy" :data-url="form.title + '：' + form.val">
                                    <text :class="valItem === search ? 'text-red text-bold' : ''" v-for="(valItem, index) in form.valArr" :key="index">{{ valItem }}</text>
                                </view>
                            </view>
                            <view @tap="bindUnFoldTap" :data-idx="index" v-if="item.fold && item.JOIN_FORMS.length > 3" class="fold">
                                <text class="icon-unfold margin-right-xs"></text>
                                更多资料...
                            </view>

                            <view @tap="bindFoldTap" :data-idx="index" v-if="!item.fold && item.JOIN_FORMS.length > 3" class="fold">
                                <text class="icon-fold margin-right-xs"></text>
                                收起
                            </view>

                            <view class="info-item add-time">
                                <view class="title text-grey">提交/变更</view>
                                <view class="mao text-grey">：</view>
                                <view class="content text-grey">{{ item.JOIN_EDIT_TIME }}</view>
                            </view>

                            <view class="oprt">
                                <block v-if="item.JOIN_STATUS == 1">
                                    <view v-if="item.JOIN_IS_CHECKIN == 0" @tap="bindCheckinTap" :data-idx="index" data-flag="1" class="btn bg-purple margin-right-s light">
                                        签到核销
                                    </view>

                                    <view v-else @tap="bindCheckinTap" :data-idx="index" data-flag="0" class="btn bg-grey light margin-right-s">取消签到</view>
                                </block>

                                <block v-if="item.JOIN_STATUS == 1">
                                    <view @tap="bindCancelTap" :data-idx="index" data-status="99" :data-old="item.JOIN_STATUS" class="btn bg-grey light margin-right-s">
                                        取消预约
                                    </view>
                                </block>

                                <block v-if="item.JOIN_STATUS == 10 || item.JOIN_STATUS == 99">
                                    <view @tap="bindStatusTap" :data-idx="index" data-status="1" :data-old="item.JOIN_STATUS" class="btn bg-olive light margin-right-s">
                                        恢复预约
                                    </view>
                                </block>

                                <view @tap="bindDelTap" :data-idx="index" class="btn bg-orange light margin-right-s">删除</view>
                            </view>
                        </view>

                        <view class="no">{{ index + 1 }}</view>
                    </view>
                </view>
                <!-- List END -->

                <!-- load begin -->

                <!-- parse <template is="listLoadTpl" :data="dataList,skin:'text-grey',noHint:'暂无记录'"/> -->
                <block name="listLoadTpl">
                    <view v-if="!dataList || (dataList && dataList.page < dataList.count)" :class="'load text-grey loading ' + 'text-grey'"></view>
                    <view v-if="dataList && dataList.page > 1 && dataList.page == dataList.count" :class="'load text-grey over ' + 'text-grey'"></view>

                    <block v-if="noHintImg">
                        <image style="height: 500rpx" mode="aspectFit" v-if="dataList && dataList.total == 0" :src="noHintImg" />
                    </block>

                    <block v-else>
                        <view v-if="dataList && dataList.total == 0" :class="'load text-grey ' + 'text-grey'">{{ '暂无记录' ? '暂无记录' : '暂无记录哦~' }}</view>
                    </block>

                    <view style="height: 100rpx"></view>
                </block>
                <!-- load end -->
            </cmpt-comm-list>

            <cmpt-modal
                v-if="cancelAllModalShow"
                :show.sync="cancelAllModalShow"
                type="dialog"
                title="取消所有预约"
                @click="bindCancelAllCmpt"
                class="modal-form"
                cancelText="返回"
                confirmText="确定取消"
            >
                <view class="form-group" style="padding: 0 10rpx">
                    <view class="title">
                        取消理由
                        <text class="text-grey text-mid">(选填)</text>
                        ：
                    </view>
                    <view @tap="bindClearReasonTap" style="width: 150rpx; text-align: right" class="text-grey">
                        <text class="icon-roundclose"></text>
                        清空
                    </view>
                </view>

                <view class="form-group cancel-area">
                    <textarea placeholder-class="phc" placeholder="请输入取消理由 (非必填)" style="height: 110rpx" v-model="formReason" maxlength="100"></textarea>
                </view>
            </cmpt-modal>

            <cmpt-modal
                v-if="cancelModalShow"
                :show.sync="cancelModalShow"
                type="dialog"
                title="取消预约"
                @click="bindCancelCmpt"
                class="modal-form"
                cancelText="返回"
                confirmText="确定取消"
            >
                <view class="form-group" style="padding: 0 10rpx">
                    <view class="title">
                        取消理由
                        <text class="text-grey text-mid">(选填)</text>
                        ：
                    </view>
                    <view @tap="bindClearReasonTap" style="width: 150rpx; text-align: right" class="text-grey">
                        <text class="icon-roundclose"></text>
                        清空
                    </view>
                </view>

                <view class="form-group cancel-area">
                    <textarea placeholder-class="phc" placeholder="请输入取消理由 (非必填)" style="height: 110rpx" v-model="formReason" maxlength="100"></textarea>
                </view>
            </cmpt-modal>

            <cmpt-modal
                v-if="refuseModalShow"
                :show.sync="refuseModalShow"
                type="dialog"
                title="审核不通过"
                @click="bindRefuseCmpt"
                class="modal-form"
                cancelText="返回"
                confirmText="确定"
            >
                <view class="form-group" style="padding: 0 10rpx">
                    <view class="title">
                        不通过理由
                        <text class="text-grey text-mid">(选填)</text>
                        ：
                    </view>
                    <view @tap="bindClearReasonTap" style="width: 150rpx; text-align: right" class="text-grey">
                        <text class="icon-roundclose"></text>
                        清空
                    </view>
                </view>

                <view class="form-group cancel-area">
                    <textarea
                        placeholder-class="phc"
                        placeholder="请输入审核不通过理由 (非必填)，将通知给用户"
                        style="height: 110rpx"
                        v-model="formReason"
                        maxlength="100"
                    ></textarea>
                </view>
            </cmpt-modal>
        </block>
    </view>
</template>

<script>
const AdminBiz = require('../../../../biz/admin_biz.js');
const pageHelper = require('../../../../helper/page_helper.js');
const cacheHelper = require('../../../../helper/cache_helper.js');
const helper = require('../../../../helper/helper.js');
const cloudHelper = require('../../../../helper/cloud_helper.js');
const CACHE_CANCEL_REASON = 'JOIN_CANCEL_REASON';
const CACHE_REFUSE_REASON = 'JOIN_REFUSE_REASON';
export default {
    data() {
        return {
            isLoad: false,
            isAllFold: true,
            parentDayIdx: 0,
            parentTimeIdx: 0,
            menuIdx: 0,
            meetId: '',
            mark: '',
            title: '',
            titleEn: '',
            cancelModalShow: false,
            cancelAllModalShow: false,
            refuseModalShow: false,
            formReason: '',
            curIdx: -1,
            time: '',
            params_var: '',

            dataList: {
                total: '',
                list: [],
                page: 0,
                count: 0
            },

            daysSet: '',
            search: '',
            sortType: '',
            sortItems: '',
            sortMenus: '',
            isAdmin: '',
            formindex: 0,

            form: {
                title: '',
                type: '',
                val: '',
                valArr: []
            },

            valItem: '',
            noHintImg: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        if (!AdminBiz.isAdmin(this)) {
            return;
        }

        // 附加参数
        if (options && options.meetId && options.mark) {
            //设置搜索菜单
            this.getSearchMenuFun();
            this.setData(
                {
                    meetId: options.meetId,
                    mark: options.mark,
                    parentDayIdx: options.dayidx,
                    parentTimeIdx: options.timeidx,
                    time: options.time,
                    params_var: {
                        meetId: options.meetId,
                        mark: options.mark
                    }
                },
                () =>
                    this.setData({
                        isLoad: true
                    })
            );
        }
        if (options && options.title) {
            let title = decodeURIComponent(options.title);
            this.setData({
                title,
                titleEn: options.title
            });
            uni.setNavigationBarTitle({
                title: '分时段预约名单 - ' + title
            });
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    methods: {
        url: async function (e) {
            pageHelper.url(e, this);
        },

        bindUnFoldTap: function (e) {
            let idx = pageHelper.dataset(e, 'idx');
            let dataList = this.dataList;
            dataList.list[idx].fold = false;
            this.setData({
                dataList
            });
        },

        bindFoldTap: function (e) {
            let idx = pageHelper.dataset(e, 'idx');
            let dataList = this.dataList;
            dataList.list[idx].fold = true;
            this.setData({
                dataList
            });
        },

        bindFoldAllTap: function (e) {
            let dataList = this.dataList;
            for (let k in dataList.list) {
                dataList.list[k].fold = true;
            }
            this.setData({
                isAllFold: true,
                dataList
            });
        },

        bindUnFoldAllTap: function (e) {
            let dataList = this.dataList;
            for (let k in dataList.list) {
                dataList.list[k].fold = false;
            }
            this.setData({
                isAllFold: false,
                dataList
            });
        },

        bindCopyTap: function (e) {
            let idx = pageHelper.dataset(e, 'idx');
            let forms = this.dataList.list[idx].JOIN_FORMS;
            let ret = '';
            ret += `项目：${this.dataList.list[idx].JOIN_MEET_TITLE}\r`;
            ret += `时段：${this.dataList.list[idx].JOIN_MEET_DAY} ${this.dataList.list[idx].JOIN_MEET_TIME_START}～${this.dataList.list[idx].JOIN_MEET_TIME_END}\r`;
            for (let k in forms) {
                ret += forms[k].title + '：' + forms[k].val + '\r';
            }
            uni.setClipboardData({
                data: ret,
                success(res) {
                    uni.getClipboardData({
                        success(res) {
                            pageHelper.showSuccToast('已复制到剪贴板');
                        }
                    });
                }
            });
        },

        bindCancelTap: function (e) {
            this.setData({
                formReason: cacheHelper.get(CACHE_CANCEL_REASON) || '',
                curIdx: pageHelper.dataset(e, 'idx'),
                cancelModalShow: true
            });
        },

        bindCancelAllTap: function (e) {
            this.setData({
                formReason: '',
                cancelAllModalShow: true
            });
        },

        bindRefuseTap: function (e) {
            this.setData({
                formReason: cacheHelper.get(CACHE_REFUSE_REASON) || '',
                curIdx: pageHelper.dataset(e, 'idx'),
                refuseModalShow: true
            });
        },

        bindCancelCmpt: async function () {
            let e = {
                currentTarget: {
                    dataset: {
                        status: 99,
                        idx: this.curIdx
                    }
                }
            };
            cacheHelper.set(CACHE_CANCEL_REASON, this.formReason, 31536000);
            await this.bindStatusTap(e);
        },

        bindCancelAllCmpt: async function () {
            try {
                let params = {
                    reason: this.formReason,
                    meetId: this.meetId,
                    timeMark: this.mark
                };
                let opt = {
                    title: '预约记录取消中'
                };
                await cloudHelper.callCloudSumbit('admin/meet_cancel_time_join', params, opt).then((res) => {
                    let callback = () => {
                        let parent = pageHelper.getPrevPage(2);
                        if (parent) {
                            let daysSet = parent.data.daysSet;
                            daysSet[this.parentDayIdx].times[this.parentTimeIdx].stat = res.data;
                            parent.setData({
                                daysSet
                            });
                        }
                        uni.redirectTo({
                            url: `admin_meet_join?meetId=${this.meetId}&mark=${this.mark}&title=${this.titleEn}&time=${this.time}&dayidx=${this.parentDayIdx}&timeidx=${this.parentTimeIdx}`
                        });
                    };
                    pageHelper.showSuccToast('取消成功', 1500, callback);
                });
            } catch (err) {
                console.log('CatchClause', err);
                console.log('CatchClause', err);
                console.log(err);
            }
        },

        bindRefuseCmpt: async function () {
            let e = {
                currentTarget: {
                    dataset: {
                        status: 8,
                        idx: this.curIdx
                    }
                }
            };
            cacheHelper.set(CACHE_REFUSE_REASON, this.formReason, 31536000);
            await this.bindStatusTap(e);
        },

        bindCheckinTap: async function (e) {
            let flag = Number(pageHelper.dataset(e, 'flag'));
            let callback = async () => {
                let idx = Number(pageHelper.dataset(e, 'idx'));
                let dataList = this.dataList;
                let joinId = dataList.list[idx]._id;
                let params = {
                    joinId,
                    flag
                };
                let opts = {
                    title: '处理中'
                };
                try {
                    await cloudHelper.callCloudSumbit('admin/join_checkin', params, opts).then((res) => {
                        let cb = () => {
                            let sortIndex = this.zpSelectComponent('#cmpt-comm-list').getSortIndex();
                            if (sortIndex >= 10 && !this.search) {
                                // 全部或者检索的结果
                                dataList.list.splice(idx, 1);
                                dataList.total--;
                            } else {
                                dataList.list[idx].JOIN_IS_CHECKIN = flag;
                            }
                            this.setData({
                                dataList
                            });
                        };
                        pageHelper.showSuccToast('操作成功', 1000, cb);
                    });
                } catch (err) {
                    console.log('CatchClause', err);
                    console.log('CatchClause', err);
                    console.error(err);
                }
            };
            if (flag == 1) pageHelper.showConfirm('确认「签到核销」？', callback);
            else if (flag == 0) {
                pageHelper.showConfirm('确认「取消签到」？', callback);
            }
        },

        bindDelTap: async function (e) {
            let callback = async () => {
                let idx = Number(pageHelper.dataset(e, 'idx'));
                let dataList = this.dataList;
                let joinId = dataList.list[idx]._id;
                let params = {
                    joinId
                };
                let opts = {
                    title: '删除中'
                };
                try {
                    await cloudHelper.callCloudSumbit('admin/join_del', params, opts).then((res) => {
                        let cb = () => {
                            let dataList = this.dataList;
                            dataList.list.splice(idx, 1);
                            dataList.total--;
                            this.setData({
                                dataList
                            });
                            let parent = pageHelper.getPrevPage(2);
                            if (parent) {
                                let daysSet = parent.data.daysSet;
                                daysSet[this.parentDayIdx].times[this.parentTimeIdx].stat = res.data;
                                parent.setData({
                                    daysSet
                                });
                            }
                        };
                        pageHelper.showSuccToast('删除成功', 1000, cb);
                    });
                } catch (err) {
                    console.log('CatchClause', err);
                    console.log('CatchClause', err);
                    console.error(err);
                }
            };
            pageHelper.showConfirm('确认删除该预约记录？ 删除后用户将无法查询到本预约记录', callback);
        },

        bindStatusTap: async function (e) {
            let status = Number(pageHelper.dataset(e, 'status'));
            let oldStatus = Number(pageHelper.dataset(e, 'old'));
            let callback = async () => {
                let idx = Number(pageHelper.dataset(e, 'idx'));
                let dataList = this.dataList;
                let joinId = dataList.list[idx]._id;
                let params = {
                    joinId,
                    status,
                    reason: this.formReason
                };
                let opts = {
                    title: '处理中'
                };
                try {
                    await cloudHelper.callCloudSumbit('admin/join_status', params, opts).then((res) => {
                        pageHelper.showSuccToast('操作成功', 1000);
                        let sortIndex = this.zpSelectComponent('#cmpt-comm-list').getSortIndex();
                        if (sortIndex != -1 && sortIndex != 5 && !this.search) {
                            // 全部或者检索的结果
                            dataList.list.splice(idx, 1);
                            dataList.total--;
                        } else {
                            dataList.list[idx].JOIN_REASON = this.formReason;
                            dataList.list[idx].JOIN_STATUS = status;
                            dataList.list[idx].JOIN_IS_CHECKIN = 0;
                        }
                        this.setData({
                            cancelModalShow: false,
                            refuseModalShow: false,
                            formReason: '',
                            curIdx: -1,
                            dataList
                        });
                        let parent = pageHelper.getPrevPage(2);
                        if (parent) {
                            let daysSet = parent.data.daysSet;
                            daysSet[this.parentDayIdx].times[this.parentTimeIdx].stat = res.data;
                            parent.setData({
                                daysSet
                            });
                        }
                    });
                } catch (err) {
                    console.log('CatchClause', err);
                    console.log('CatchClause', err);
                    console.error(err);
                }
            };
            switch (status) {
                case 99:
                    //直接取消
                    await callback();
                    break;
                case 1: {
                    if (oldStatus == 10) pageHelper.showConfirm('确认变更为「预约成功」？', callback);
                    else if (oldStatus == 99) {
                        pageHelper.showConfirm('确认恢复为「预约成功」状态？', callback);
                    }
                    break;
                }
            }
        },

        bindCommListCmpt: function (e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            if (helper.isDefined(e.detail.search)) {
                this.setData({
                    search: '',
                    sortType: ''
                });
            } else {
                let dataList = e.detail.dataList;
                if (dataList) {
                    for (let k in dataList.list) {
                        dataList.list[k].fold = this.isAllFold;
                    }
                }
                this.setData({
                    dataList
                });
                if (e.detail.sortType) {
                    this.setData({
                        sortType: e.detail.sortType
                    });
                }
            }
        },

        // 修改与展示状态菜单
        getSearchMenuFun: function () {
            let sortItems = [];
            let sortMenus = [
                {
                    label: '全部',
                    type: '',
                    value: ''
                },
                {
                    label: `成功`,
                    type: 'status',
                    value: 1
                },
                {
                    label: `已取消`,
                    type: 'status',
                    value: 1099
                },
                {
                    label: `已签到`,
                    type: 'checkin',
                    value: 1
                },
                {
                    label: `未签到`,
                    type: 'checkin',
                    value: 0
                }
            ];
            this.setData({
                sortItems,
                sortMenus
            });
        },

        bindClearReasonTap: function (e) {
            this.setData({
                formReason: ''
            });
        }
    }
};
</script>
<style>
@import './admin_meet_join.css';
@import 'undefined';
</style>
